package com.meida.module.arc.provider.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.SneakyThrows;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.ofdrw.core.annotation.pageannot.AnnotType;
import org.ofdrw.core.basicType.ST_Box;
import org.ofdrw.font.FontName;
import org.ofdrw.layout.OFDDoc;
import org.ofdrw.layout.element.canvas.FontSetting;
import org.ofdrw.reader.OFDReader;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.Font;
import java.awt.Image;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Author: FuGui Wang
 * @Description: PDF增加水印工具类
 * @Date 2022/12/14
 * @Version V1.1.0
 */
public class FileWaterMarkUtil {

    //https://www.jianshu.com/p/ce1092300d0f

    /**
     * pdf添加水印
     *
     * @param inputFile     需要添加水印的文件
     * @param text          需要添加的水印文字
     * @param fontUrl       水印文本字体文件路径
     * @param opacity       水印字体透明度
     * @param fontSize      水印字体大小
     * @param angle         水印倾斜角度（0-360）
     * @param heightDensity 数值越大每页竖向水印越少
     * @param widthDensity  数值越大每页横向水印越少
     * @return
     * @throws Exception
     */
    public static ByteArrayOutputStream addWaterMark(String inputFile, String text, String fontUrl, float opacity,
                                                     int fontSize, int angle, float heightDensity, float widthDensity) throws Exception {
        // 0.读取原pdf
        PdfReader reader = new PdfReader(inputFile);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, bos);

        // 1.准备 字符串的高度、长度、透明度、字体类型 等参数
        JLabel label = new JLabel();
        FontMetrics metrics;
        int textH = 0;
        int textW = 0;
        label.setText(text);
        metrics = label.getFontMetrics(label.getFont());
        //字符串的高,   只和字体有关
        textH = metrics.getHeight();
        //字符串的宽
        textW = metrics.stringWidth(label.getText());
        // 水印透明度、字体设置
        PdfGState gs = new PdfGState();
        // 设置填充字体不透明度为0.2f
        gs.setFillOpacity(opacity);
        // 准备字体类型
        BaseFont base = BaseFont.createFont(fontUrl, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        // 2.循环PDF，每页添加水印
        PdfContentByte waterMar = null;
        com.itextpdf.text.Rectangle pageRect = null;
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            pageRect = reader.getPageSizeWithRotation(i);
            // 设置透明度、字体类型、字体大小
            waterMar = stamper.getOverContent(i);
            waterMar.saveState();
            waterMar.setGState(gs);
            waterMar.setFontAndSize(base, fontSize);
            // 开始添加水印
            waterMar.beginText();
            // 添加水印
            for (float height = textH; height < pageRect.getHeight() * 2; height = height + textH * heightDensity) {
                for (float width = textW; width < pageRect.getWidth() * 1.5 + textW; width = width + textW * widthDensity) {
                    waterMar.showTextAligned(Element.ALIGN_LEFT, text, width - textW, height - textH, angle);
                }
            }
            // 设置水印颜色
            waterMar.setColorFill(BaseColor.GRAY);
            //结束设置
            waterMar.endText();
            waterMar.stroke();
        }
        stamper.close();

        return bos;
    }

    /**
     * 给PDF添加水印
     *
     * @param inputFile     原文件路径+名称
     * @param outputFile    添加水印后输出文件保存的路径+名称
     * @param waterMarkName 添加水印的内容
     */
    public static String PDFAddWatermark(String inputFile, String outputFile, String waterMarkName, String waterMarkPlus, float fillOpacity, int fontSize, int rotate, boolean footerFlag, String footer) {
        try {
            // 水印的高和宽（参数可调节）
            int textH = 75;
            int textW = 170;
            // 间隔距离（参数可调节）
            int interval = 5;

            // 切记这里的参数是文件的路径 ，路径必须是双斜杠的如F:\\test.pdf，不能是F:/test.pdf 或者F:\test.pdf
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));

            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(fillOpacity);//改透明度
            gs.setStrokeOpacity(0.4f);
            int total = reader.getNumberOfPages() + 1;
            JLabel label = new JLabel();
            PdfContentByte under = null;

            // 可添加多个水印
            Rectangle pageRect = null;
            FontMetrics metrics;

            label.setText(waterMarkName);
            metrics = label.getFontMetrics(label.getFont());
            //得到文字的宽高
            textH = metrics.getHeight();
            textW = metrics.stringWidth(label.getText());
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                // 在内容上方加水印
                under = stamper.getOverContent(i);
                // 在内容下方加水印
                //under = stamper.getUnderContent(i);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                //设置水印文字颜色
                under.setColorFill(BaseColor.GRAY);
                //设置水印文字和大小
                under.setFontAndSize(base, fontSize);
                //这个position主要是为了在换行加水印时能往右偏移起始坐标
                /*int position = 0;
                for (int height = interval + textH; height < pageRect.getHeight();
                     height = height + textH * 3) {
                    for (int width = interval + textW - position * 150; width < pageRect.getWidth() + textW;
                         width = width + textW) {
                        // 水印文字成30度角倾斜
                        under.showTextAligned(Element.ALIGN_LEFT
                                , waterMarkName, width - textW,
                                height - textH, rotate);
                    }
                    position++;
                }*/
                for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 10) {
                    for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW * 5) {
                        //水印文字成21度角倾斜
                        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, rotate);
                        if (StrUtil.isNotEmpty(waterMarkPlus)) {
                            under.showTextAligned(Element.ALIGN_LEFT, waterMarkPlus, width - textW, height - textH - metrics.getHeight() - 5, rotate);
                        }
                    }
                }

                // 添加水印文字
                under.endText();
                under.stroke();
            }

            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
            outputFile = inputFile;
        } finally {
            String out = outputFile.split("\\.")[0] + "footer" + "." + outputFile.split("\\.")[1];
            if (footerFlag) {
                PDFAddFooter(outputFile, out, footer);
            }
            outputFile = out;

        }
        return outputFile;

    }

    /**
     * 图片添加水印
     *
     * @param srcImgPath       需要添加水印的图片的路径
     * @param outImgPath       添加水印后图片输出路径
     * @param markContentColor 水印文字的颜色
     * @param waterMarkContent 水印的文字
     */
    public static void mark(String srcImgPath, String outImgPath, Color markContentColor, String waterMarkContent) {
        try {
            // 读取原图片信息
            File srcImgFile = new File(srcImgPath);
            Image srcImg = ImageIO.read(srcImgFile);
            int srcImgWidth = srcImg.getWidth(null);
            int srcImgHeight = srcImg.getHeight(null);
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            // Font font = new Font("Courier New", Font.PLAIN, 12);
            Font font = new Font("宋体", Font.PLAIN, 20);
            g.setColor(markContentColor); // 根据图片的背景设置水印颜色            g.setFont(font);
            int x = srcImgWidth - getWatermarkLength(waterMarkContent, g) - 3;
            int y = srcImgHeight - 3;
            // int x = (srcImgWidth - getWatermarkLength(watermarkStr, g)) / 2;
            // int y = srcImgHeight / 2;
            g.drawString(waterMarkContent, x, y);
            g.dispose();
            // 输出图片
            FileOutputStream outImgStream = new FileOutputStream(outImgPath);
            ImageIO.write(bufImg, "jpg", outImgStream);
            outImgStream.flush();
            outImgStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param inputFile     源文件
     * @param outputFile    输出文件
     * @param waterMarkName 水印文字
     * @param waterMarkPlus 水印扩展内容(用户ID或者日期)
     * @param fillOpacity   透明度
     * @param fontSize      字体大小
     * @param rotate        倾斜角度
     * @param imgFilePath   水印图片路径
     * @param footerFlag    是否生成页脚
     * @param footer        页脚内容
     * @return
     */
    public static String PDFAddTextImgWatermark(String inputFile, String outputFile, String waterMarkName, String waterMarkPlus, float fillOpacity, int fontSize, int rotate, String imgFilePath, boolean footerFlag, String footer) {
        try {
            // 间隔距离（参数可调节）
            int interval = 5;

            // 切记这里的参数是文件的路径 ，路径必须是双斜杠的如F:\\test.pdf，不能是F:/test.pdf 或者F:\test.pdf
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));

            int total = reader.getNumberOfPages() + 1;

            com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(new URL(imgFilePath));

            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(fillOpacity);
            gs.setStrokeOpacity(0.4f);
            JLabel label = new JLabel();
            label.setText(waterMarkName);
            FontMetrics metrics = label.getFontMetrics(label.getFont());
            //得到文字的宽高
            int textH = metrics.getHeight();
            int textW = metrics.stringWidth(label.getText());

            PdfContentByte under = null;
            for (int i = 1; i < total; i++) {
                // 可添加多个水印
                Rectangle pageRect = reader.getPageSizeWithRotation(i);
                // 在内容上方加水印
                under = stamper.getOverContent(i);
                // 在内容下方加水印
                //under = stamper.getUnderContent(i);
                //under.saveState();
                under.setGState(gs);
                under.beginText();
                //设置水印文字颜色
                under.setColorFill(BaseColor.GRAY);
                //设置水印文字和大小
                under.setFontAndSize(baseFont, fontSize);
                //这个position主要是为了在换行加水印时能往右偏移起始坐标
               /* int position = 0;
                for (int height = interval + textH; height < pageRect.getHeight();
                     height = height + textH * 3) {
                    for (int width = interval + textW - position * 150; width < pageRect.getWidth() + textW;
                         width = width + textW) {
                        // 水印文字成30度角倾斜
                        under.showTextAligned(Element.ALIGN_LEFT
                                , waterMarkName, width - textW,
                                height - textH, rotate);
                    }
                    position++;
                }*/
                for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 10) {

                    for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW * 5) {
                        //水印文字成21度角倾斜
                        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, rotate);
                        if (StrUtil.isNotEmpty(waterMarkPlus)) {
                            under.showTextAligned(Element.ALIGN_LEFT, waterMarkPlus, width - textW, height - textH - metrics.getHeight() - 5, rotate);
                        }
                    }
                }

                // 设置旋转角度
                image.setRotationDegrees(rotate);
                float width = image.getWidth();
                if (width > 575) {
                    width = 575;
                }
                Rectangle rect = new Rectangle(0, 0, width, image.getHeight());
                image.scaleToFit(rect);
                image.setAbsolutePosition(0, 0);
                under.addImage(image);

            }
            under.endText();

            under.stroke();
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
            outputFile = inputFile;
        } finally {
            String out = outputFile.split("\\.")[0] + "footer" + "." + outputFile.split("\\.")[1];
            if (footerFlag) {
                PDFAddFooter(outputFile, out, footer);
                outputFile = out;

                /*try {
                    File file2 = new File(outputFile);
                    PDDocument pdDocument = PDDocument.load(file2);
                    int pageCount = pdDocument.getNumberOfPages();
                    // 创建一个文档
                    Document document = new Document(PageSize.A4);
                    // pdf输出流
                    OutputStream outputStream = new FileOutputStream(out);
                    PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);
                    document.open();
                    // 添加页眉页脚
                    pdfWriter.setPageEvent(new MyHeaderFooter(footer));
                    PdfContentByte cb = pdfWriter.getDirectContent();

                    PdfReader reader = new PdfReader(new FileInputStream(file2));
                    for (int i = 1; i <= pageCount; i++) {
                        PdfImportedPage page = pdfWriter.getImportedPage(reader, i);
                        cb.addTemplate(page, 0, 0);
                        document.newPage();
                    }

                    document.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (DocumentException e) {
                    e.printStackTrace();
                }*/
            }
            return outputFile;

        }

    }

    /**
     * 获取水印文字总长度
     *
     * @param waterMarkContent 水印的文字
     * @param g
     * @return 水印文字总长度
     */
    public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
    }

    private static int getNumberOfPages(String pdfFilePath) throws IOException {
        PdfReader reader = new PdfReader(pdfFilePath);
        return reader.getNumberOfPages();
    }

    /**
     * 给图片添加水印
     *
     * @param iconPath   水印图片路径
     * @param srcImgPath 源图片路径
     * @param targerPath 目标图片路径
     */
    public static void markImageByIcon(String iconPath, String srcImgPath, String targerPath) {
        markImageByIcon(iconPath, srcImgPath, targerPath, null);
    }

    /**
     * 给图片添加水印、可设置水印图片旋转角度
     *
     * @param iconPath   水印图片路径
     * @param srcImgPath 源图片路径
     * @param targerPath 目标图片路径
     * @param degree     水印图片旋转角度
     */
    public static void markImageByIcon(String iconPath, String srcImgPath, String targerPath, Integer degree) {
        OutputStream os = null;
        try {
            Image srcImg = ImageIO.read(new File(srcImgPath));
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null),
                    BufferedImage.TYPE_INT_RGB);            // 得到画笔对象
            // Graphics g= buffImg.getGraphics();
            Graphics2D g = buffImg.createGraphics();            // 设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH), 0,
                    0, null);
            if (null != degree) {
                // 设置水印旋转
                g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
            }            // 水印图象的路径 水印一般为gif或者png的，这样可设置透明度
            ImageIcon imgIcon = new ImageIcon(iconPath);            // 得到Image对象。
            Image img = imgIcon.getImage();
            float alpha = 0.5f; // 透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));            // 表示水印图片的位置
            g.drawImage(img, 150, 300, null);
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            g.dispose();
            os = new FileOutputStream(targerPath);            // 生成图片
            ImageIO.write(buffImg, "JPG", os);
            System.out.println("图片完成添加Icon印章。。。。。。");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String PDFAddImgWaterMaker(String inputFile, String outputFile, String imgFilePath, float fillOpacity, int rotate, boolean footerFlag, String footer) {
        try {
            PdfReader reader = new PdfReader(inputFile);
            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
            PdfGState gs1 = new PdfGState();
            // 设置透明度
            gs1.setFillOpacity(fillOpacity);
            com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(imgFilePath);
            // 获取PDF页数
            int num = reader.getNumberOfPages();
            PdfContentByte under;
            for (int i = 1; i <= num; i++) {
                PdfContentByte pdfContentByte = stamper.getOverContent(i);
                // 获得PDF最顶层
                under = stamper.getOverContent(i);
                pdfContentByte.setGState(gs1);
                // 设置旋转角度
                image.setRotationDegrees(rotate);// 旋转 角度
                // 设置等比缩放
                under.setColorFill(BaseColor.GRAY);
                float width = image.getWidth();
                if (width > 575) {
                    width = 575;
                }
                Rectangle rect = new Rectangle(0, 0, width, image.getHeight());
                image.scaleToFit(rect);
                image.setRotation(30);
                image.setAbsolutePosition(0, 0);
                pdfContentByte.addImage(image);

                under.endText();
                under.stroke();
            }
            stamper.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
            outputFile = inputFile;

        } finally {
            String out = outputFile.split("\\.")[0] + "footer" + "." + outputFile.split("\\.")[1];
            if (footerFlag) {
                PDFAddFooter(outputFile, out, footer);
            }
            outputFile = out;
        }
        return outputFile;
    }


    /**
     * @param inputFile  输入路径
     * @param outputFile 输出路径
     * @param imgPath    图片路径
     * @param position   加章位置: 1左上角、0中间、2右上角
     */
    public static String OFDAddImgWatermark(String inputFile, String outputFile, String imgPath, float fillOpacity, int fontSize, String position, int rotate) throws IOException, BadElementException {
        Path srcP = Paths.get(inputFile);
        Path outP = Paths.get(outputFile);
        com.itextpdf.text.Image img = com.itextpdf.text.Image.getInstance(new URL(imgPath));
        //水印图片下载本地
        File localImage = downloadImage(imgPath);
        Path imgPathPath = localImage.toPath();
        try (OFDReader reader = new OFDReader(srcP); OFDDoc ofdDoc = new OFDDoc(reader, outP)) {
            // 水印的高和宽（参数可调节）
            int textH = 5;
            int textW = 25;
            // 间隔距离（参数可调节）
            int interval = 5;

            Double width1 = ofdDoc.getPageLayout().getWidth();
            Double height1 = ofdDoc.getPageLayout().getHeight();
            org.ofdrw.layout.edit.Annotation annotation1 = new org.ofdrw.layout.edit.Annotation(new ST_Box(0d, 0d, width1, height1), AnnotType.Watermark, ctx -> {
                FontSetting setting = new FontSetting(8, FontName.SimSun.font());
                ctx.setFillColor(170, 160, 165).setFont(setting).setGlobalAlpha(new Double(fillOpacity));
                float imageWidth = img.getWidth();
                float imageHeight = img.getHeight();
                // 图片水印
                if (position.equals("leftTop")) {//左上角
                    ctx.drawImage(imgPathPath, 0, 0, imageWidth / 3.5, imageHeight / 3.5);
                } else if (position.equals("middle")) {//居中
                    ctx.drawImage(imgPathPath, (width1 - imageWidth / 3.5) / 2, (height1 - imageHeight / 3.5) / 2, img.getWidth() / 3.5, imageHeight / 3.5);
                } else if (position.equals("leftBottom")) {//左下
                    ctx.drawImage(imgPathPath, 0, height1 - imageHeight / 3.5, img.getWidth() / 3.5, imageHeight / 3.5);
                } else if (position.equals("rightBottom")) {//右下
                    ctx.drawImage(imgPathPath, width1 - imageWidth / 3.5, height1 - imageHeight / 3.5, img.getWidth() / 3.5, imageHeight / 3.5);
                } else if (position.equals("rightTop")) {//右上角
                    ctx.drawImage(imgPathPath, width1 - imageWidth / 3.5, 0, img.getWidth() / 3.5, imageHeight / 3.5);
                } else if (position.equals("tile")) {//平铺
                    double w = imageWidth / 3.5;
                    for (int j = 0; j < width1; j += w) {
                        ctx.drawImage(imgPathPath, j, 0, imageWidth / 3.5, imageHeight / 3.5);
                        double h = imageHeight / 3.5;
                        for (int i = 0; i < height1; i += h) {
                            ctx.drawImage(imgPathPath, j, i + h, imageWidth / 3.5, imageHeight / 3.5);
                        }
                    }

                } else if (position.equals("fill")) {//填充
                    ctx.drawImage(imgPathPath, 0, (height1 - imageHeight / 3.5) / 2, width1, height1);
                }
                else {//默认居中
                    ctx.drawImage(imgPathPath, (width1 - imageWidth / 3.5) / 2, (height1 - imageHeight / 3.5) / 2, img.getWidth() / 3.5, imageHeight / 3.5);
                }
            });

            int Pages = reader.getNumberOfPages();
            for (int i = 1; i <= Pages; i++) {
                ofdDoc.addAnnotation(i, annotation1);
            }

        }
        catch (Exception e){
            e.printStackTrace();
        }
        return outP.toAbsolutePath().toString();
    }

    public static String OFDAddWatermark(String inputFile, String outputFile,String waterMarkName,String waterMarkPlus,float fillOpacity, int fontSize, String position, int rotate) throws IOException, BadElementException {
        Path srcP = Paths.get(inputFile);
        Path outP = Paths.get(outputFile);
        try (OFDReader reader = new OFDReader(srcP); OFDDoc ofdDoc = new OFDDoc(reader, outP)) {
            // 水印的高和宽（参数可调节）
            int textH = 5;
            int textW = 25;
            // 间隔距离（参数可调节）
            int interval = 5;

            Double width1 = ofdDoc.getPageLayout().getWidth();
            Double height1 = ofdDoc.getPageLayout().getHeight();
            org.ofdrw.layout.edit.Annotation annotation = new org.ofdrw.layout.edit.Annotation(new ST_Box(0d, 0d, width1, height1), AnnotType.Watermark, ctx -> {
                FontSetting setting = new FontSetting(fontSize-10, FontName.SimSun.font());
                ctx.setFillColor(170, 160, 165).setFont(setting).setGlobalAlpha(new Double(fillOpacity));
                for (int height = interval + textH; height < height1; height = height + textH * 10) {
                    for (int width = interval + textW; width < width1 + textW; width = width + textW * 5) {
                        ctx.save();
                        ctx.rotate(rotate);
                        ctx.translate(width - textW, height - textH);
                        ctx.fillText(waterMarkName, 10, 10);
                        ctx.restore();

                        ctx.save();
                        ctx.rotate(rotate);
                        ctx.translate(width - textW, height - textH+20);
                        ctx.fillText(waterMarkPlus, 10, 10);
                        ctx.restore();
                    }
                }
            });

            int Pages = reader.getNumberOfPages();
            for (int i = 1; i <= Pages; i++) {
                ofdDoc.addAnnotation(i, annotation);
            }

        }
        catch (Exception e){
            e.printStackTrace();
        }
        return outP.toAbsolutePath().toString();
    }

    /**
     *
     * @param inputFile 源文件
     * @param outputFile 输出文件
     * @param imgPath  水印图片
     * @param position  水印图片位置
     * @return
     * @throws IOException
     * @throws BadElementException
     */
    public static String OFDAddImgAndWatermark(String inputFile, String outputFile, String imgPath,String waterMarkName,String waterMarkPlus,float fillOpacity, int fontSize, String position, int rotate) throws  Exception {
        Path srcP = Paths.get(inputFile);
        Path outP = Paths.get(outputFile);
        com.itextpdf.text.Image img = com.itextpdf.text.Image.getInstance(new URL(imgPath));
        //水印图片下载本地
        File localImage=downloadImage(imgPath);
        Path imgPathPath = localImage.toPath();
        try (OFDReader reader = new OFDReader(srcP); OFDDoc ofdDoc = new OFDDoc(reader, outP)) {
            // 水印的高和宽（参数可调节）
            int textH = 5;
            int textW = 30;
            // 间隔距离（参数可调节）
            int interval = 30;

            Double width1 = ofdDoc.getPageLayout().getWidth();
            Double height1 = ofdDoc.getPageLayout().getHeight();
            org.ofdrw.layout.edit.Annotation annotation = new org.ofdrw.layout.edit.Annotation(new ST_Box(0d, 0d, width1, height1), AnnotType.Watermark, ctx -> {
                FontSetting setting = new FontSetting(fontSize / 4, FontName.SimSun.font());
                ctx.setFillColor(170, 160, 165).setFont(setting).setGlobalAlpha(new Double(fillOpacity));
                for (int height = interval + textH; height < height1; height = height + textH * 10) {
                    for (int width = interval + textW; width < width1 + textW; width = width + textW * 5) {
                        ctx.save();
                        ctx.rotate(rotate);
                        ctx.translate(width - textW, height - textH);
                        ctx.fillText(waterMarkName, 10, 10);
                        ctx.restore();

                        ctx.save();
                        ctx.rotate(rotate);
                        ctx.translate(width - textW - 10, height - textH + fontSize / 6);
                        ctx.fillText(waterMarkPlus, 20, 20);
                        ctx.restore();
                    }
                }
            });
            org.ofdrw.layout.edit.Annotation annotation1 = new org.ofdrw.layout.edit.Annotation(new ST_Box(0d, 0d, width1, height1), AnnotType.Watermark, ctx -> {
                FontSetting setting = new FontSetting(8, FontName.SimSun.font());
                ctx.setFillColor(170, 160, 165).setFont(setting).setGlobalAlpha(new Double(fillOpacity));
                float imageWidth = img.getWidth();
                float imageHeight = img.getHeight();
                // 图片水印
                if (position.equals("leftTop")) {//左上角
                    ctx.drawImage(imgPathPath, 0, 0, imageWidth / 3.5, imageHeight / 3.5);
                } else if (position.equals("middle")) {//居中
                    ctx.drawImage(imgPathPath, (width1 - imageWidth / 3.5) / 2, (height1 - imageHeight / 3.5) / 2, img.getWidth() / 3.5, imageHeight / 3.5);
                } else if (position.equals("leftBottom")) {//左下
                    ctx.drawImage(imgPathPath, 0, height1 - imageHeight / 3.5, img.getWidth() / 3.5, imageHeight / 3.5);
                } else if (position.equals("rightBottom")) {//右下
                    ctx.drawImage(imgPathPath, width1 - imageWidth / 3.5, height1 - imageHeight / 3.5, img.getWidth() / 3.5, imageHeight / 3.5);
                } else if (position.equals("rightTop")) {//右上角
                    ctx.drawImage(imgPathPath, width1 - imageWidth / 3.5, 0, img.getWidth() / 3.5, imageHeight / 3.5);
                } else if (position.equals("fill")) {//填充
                    ctx.drawImage(imgPathPath, 0, (height1 - imageHeight / 3.5) / 2, width1, height1);
                } else if (position.equals("tile")) {//平铺
                    double w = imageWidth / 3.5;
                    for (int j = 0; j < width1; j += w) {
                        ctx.drawImage(imgPathPath, j, 0, imageWidth / 3.5, imageHeight / 3.5);
                        double h = imageHeight / 3.5;
                        for (int i = 0; i < height1; i += h) {
                            ctx.drawImage(imgPathPath, j, i + h, imageWidth / 3.5, imageHeight / 3.5);
                        }
                    }

                } else {//默认居中
                    ctx.drawImage(imgPathPath, (width1 - imageWidth / 3.5) / 2, (height1 - imageHeight / 3.5) / 2, img.getWidth() / 3.5, imageHeight / 3.5);
                }
            });

            int Pages = reader.getNumberOfPages();
            for (int i = 1; i <= Pages; i++) {
                ofdDoc.addAnnotation(i, annotation);
                ofdDoc.addAnnotation(i, annotation1);
            }
            ofdDoc.close();
        }
        catch (Exception e){

        }
        return outP.toAbsolutePath().toString();
    }


    //为了使文字向左移动5像素
    private static int interval = -5;

    /**
     * PDF加文字水印
     *
     * @param inputFile     PDF文件输入路径
     * @param outputFile    PDF文件输出路径
     * @param waterMarkName 自定义水印
     */
    public static void waterMarkPdf(String inputFile, String outputFile, String waterMarkName) {
        //根据水印文字长度，更改水印文字大小
        int size = 0;
        if (waterMarkName.length() <= 13) {
            size = 50;
        } else if (waterMarkName.length() > 13 && waterMarkName.length() <= 33) {
            size = 35;
        } else {
            size = 20;
        }
        try {
            PdfReader reader = new PdfReader(inputFile);
            FileOutputStream outputStream = new FileOutputStream(outputFile);
            PdfStamper stamper = new PdfStamper(reader, outputStream);
            //设置文字样式
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);

            Rectangle pageRect = null;

            PdfGState gs = new PdfGState();
            //设置透明度
            gs.setFillOpacity(0.03f);

            gs.setStrokeOpacity(0.4f);

            int total = reader.getNumberOfPages() + 1;

            JLabel label = new JLabel();

            FontMetrics metrics;

            int textH = 0;

            int textW = 0;
            //设置自定义水印
            label.setText(waterMarkName);

            metrics = label.getFontMetrics(label.getFont());

            textH = metrics.getHeight();

            textW = metrics.stringWidth(label.getText());

            PdfContentByte under = null;

            for (int i = 1; i < total; i++) {

                pageRect = reader.getPageSizeWithRotation(i);

                under = stamper.getOverContent(i);

                under.saveState();

                under.setGState(gs);

                under.beginText();

                under.setFontAndSize(base, size);

                //调整for循环的宽高可更改水印位置，高：textH 宽：textW
                for (int height = interval + textH; height < pageRect.getHeight(); height = height + textH * 10) {

                    for (int width = interval + textW; width < pageRect.getWidth() + textW; width = width + textW * 5) {
                        //水印文字成21度角倾斜
                        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, 21);
                    }
                }
                // 添加水印文字
                under.endText();
            }
            //关闭流
            stamper.close();
            outputStream.close();
            reader.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 水印透明度
    private static float alpha = 0.1f;
    // 水印文字颜色
    private static Color color = Color.RED;
    // 水印之间的间隔
    private static final int XMOVE = 80;
    // 水印之间的间隔
    private static final int YMOVE = 80;

    public static void ImageByText(File srcFile, File dstFile, Integer degree, String logoText, String logoTextPlus) {

        InputStream is = null;
        OutputStream os = null;
        try {
            long start = System.currentTimeMillis();
            // 源图片
            Image srcImg = ImageIO.read(srcFile);
            int width = srcImg.getWidth(null);// 原图宽度
            int height = srcImg.getHeight(null);// 原图高度
            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null), srcImg.getHeight(null),
                    BufferedImage.TYPE_INT_RGB);
            // 得到画笔对象
            Graphics2D g = buffImg.createGraphics();
            // 设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg.getHeight(null), Image.SCALE_SMOOTH),
                    0, 0, null);
            // 设置水印旋转
            if (null != degree) {
                g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2);
            }
            int txtLen = logoTextPlus.length();
            int FONT_SIZE = width / txtLen;
            Font font = new Font("微软雅黑", Font.BOLD, FONT_SIZE);
            // 设置水印文字颜色
            g.setColor(color);
            // 设置水印文字Font
            g.setFont(font);
            // 设置水印文字透明度
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
            int x = -width / 2;
            int y = -height / 2;
            int markWidth = FONT_SIZE * txtLen;// 字体长度
            int markHeight = FONT_SIZE;// 字体高度

            // 循环添加水印
            while (x < width * 1.5) {
                y = -height / 2;
                while (y < height * 1.5) {
                    g.drawString(logoText, x, y);
                    y += markHeight + YMOVE;
                    g.drawString(logoTextPlus, x, y);
                    y += markHeight + YMOVE;
                }
                x += markWidth + XMOVE;
            }
            // 释放资源
            g.dispose();
            // 生成图片
            os = new FileOutputStream(dstFile);
            ImageIO.write(buffImg, FileUtil.extName(srcFile), os);
            long time = System.currentTimeMillis() - start;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    //页脚
    @SneakyThrows
    public static String PDFAddFooter(String inputFile, String outputFile, String str) {

        File file2 = new File(inputFile);
        PDDocument pdDocument = PDDocument.load(file2);
        int pageCount = pdDocument.getNumberOfPages();
        // 创建一个文档
        Document document = new Document(PageSize.A4);
        // pdf输出流
        OutputStream outputStream = new FileOutputStream(outputFile);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);
        document.open();
        // 添加页眉页脚
        pdfWriter.setPageEvent(new MyHeaderFooter(str));
        PdfContentByte cb = pdfWriter.getDirectContent();

        PdfReader reader = new PdfReader(new FileInputStream(file2));
        for (int i = 1; i <= pageCount; i++) {
            PdfImportedPage page = pdfWriter.getImportedPage(reader, i);
            cb.addTemplate(page, 0, 0);
            document.newPage();
        }

        document.close();
        pdDocument.close();
        return outputFile;
    }

    public static void main(String[] args) {

        System.out.println(DateUtil.format(DateUtil.date(), "yyyy年MM月dd日 E HH时mm分ss秒"));
        try {
            //PdfWriter writer = new PdfWriter(file);// PdfWriter.getInstance(null, new FileOutputStream("/Users/mhsdong/Desktop/yycx/uploadtemp/中国少年先锋队队歌-页眉脚.pdf"));
            //writer.setPageEvent( new MyHeaderFooter());
            File file2 = new File("/Users/mhsdong/Desktop/yycx/uploadtemp/中国少年先锋队队歌.pdf");

            PDDocument pdDocument = PDDocument.load(file2);
            int pageCount = pdDocument.getNumberOfPages();
            System.out.println(pageCount);


            // 创建一个文档
            Document document = new Document(PageSize.A4);
            // pdf输出流
            OutputStream outputStream = new FileOutputStream("/Users/mhsdong/Desktop/yycx/uploadtemp/中国少年先锋队队歌-页眉脚.pdf");
            PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);
            document.open();

            // 添加页眉页脚
            //pdfWriter.setPageEvent(new MyHeaderFooter("浪里个浪"));
            pdfWriter.setPageEvent(new PDFBuilder(new String[]{"yeyeyeye左", "耶耶耶 右", "浪里个浪"}));

            PdfContentByte cb = pdfWriter.getDirectContent();

            PdfReader reader = new PdfReader(new FileInputStream(file2));
            for (int i = 1; i <= pageCount; i++) {
                PdfImportedPage page = pdfWriter.getImportedPage(reader, i);
                cb.addTemplate(page, 0, 0);
                document.newPage();
            }
            //document.add(new Paragraph("test  contents"));

            document.close();

            //waterMarkPdf("/Users/mhsdong/Desktop/yycx/uploadtemp/中国少年先锋队队歌.pdf", "/Users/mhsdong/Desktop/yycx/uploadtemp/中国少年先锋队队歌-转换水印.pdf", "涉密文件\n 2023-08-21 12:05:32");
            //PDFAddTextImgWatermark("/Users/mhsdong/Desktop/yycx/uploadtemp/中国少年先锋队队歌.pdf", "/Users/mhsdong/Desktop/yycx/uploadtemp/中国少年先锋队队歌-图文转换水印.pdf", "涉密文件", "admin  2023-08-21 14:48:18", 0.2f, 14, 30, "http://139.196.136.137:85/archive/2023/05/31/f4af28b3d18347ca8db7cb0da4141cf3.jpg");
            //PDFAddWatermark("/Users/mhsdong/Desktop/yycx/uploadtemp/中国少年先锋队队歌.pdf", "/Users/mhsdong/Desktop/yycx/uploadtemp/中国少年先锋队队歌-文章水印.pdf", "涉密文件", DateUtil.formatDateTime(DateUtil.date()), 0.4f, 18, 40);
            //PDFAddImgWaterMaker("/Users/mhsdong/Desktop/yycx/uploadtemp/中国少年先锋队队歌.pdf", "/Users/mhsdong/Desktop/yycx/uploadtemp/中国少年先锋队队歌-图水印.pdf", "http://139.196.136.137:85/archive/2023/08/21/451d212db9354b7c8b22aad9a3b6e031.jpg", 0.4f, 18);

            //OFDAddWatermark("/Users/mhsdong/Desktop/yycx/uploadtemp/网络版部署.ofd","/Users/mhsdong/Desktop/yycx/uploadtemp/网络版部署-图.ofd", "/Users/mhsdong/Desktop/印章-1.png","2");

            // 原图位置, 输出图片位置, 水印文字颜色, 水印文字
            //mark("C:/Users/liqiang/Desktop/图片/kdmt.jpg", "C:/Users/liqiang/Desktop/图片/kdmt1.jpg",   Color.red, "圖片來源:XXX");

           /* String srcImgPath = "C:/Users/liqiang/Desktop/图片/kdmt.jpg";
            String iconPath = "C:/Users/liqiang/Desktop/图片/qlq.jpeg";
            String targerPath = "C:/Users/liqiang/Desktop/图片/qlq1.jpeg";
            String targerPath2 = "C:/Users/liqiang/Desktop/图片/qlq2.jpeg";
            // 给图片添加水印
             markImageByIcon(iconPath, srcImgPath, targerPath);
            // 给图片添加水印,水印旋转-45
             markImageByIcon(iconPath, srcImgPath, targerPath2, -45);*/


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static File downloadImage(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取图片数据并保存到文件
            InputStream inputStream = connection.getInputStream();
            File imageFile = new File("temp_watermark.jpg");
            try (OutputStream outputStream = new FileOutputStream(imageFile)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
            return imageFile;
        } else {
            throw new IOException("Failed to retrieve image: HTTP error code " + responseCode);
        }
    }
}
